<script setup lang="ts">
import { onMounted, onBeforeUnmount } from 'vue';
import L from 'leaflet';
import 'leaflet/dist/leaflet.css';
import 'leaflet.polyline.snakeanim';
import { mapOptions, attribution } from '@/constants/map';
import type { Polyline, LatLngExpression } from 'leaflet';
import type { LineString, MultiLineString } from 'geojson';

// leaflet 地图实例
let map: L.Map | null = null;
//水流路径
let path: Polyline<LineString | MultiLineString, any>;

// 轨迹线数据
const latlngs: LatLngExpression[] = [
	[39.898457, 116.391844],
	[39.898595, 116.377947],
	[39.898341, 116.368001],
	[39.898063, 116.357144],
	[39.899095, 116.351934],
	[39.905871, 116.35067],
	[39.922329, 116.3498],
	[39.931017, 116.349671],
	[39.939104, 116.349225],
	[39.942233, 116.34991],
	[39.947263, 116.366892],
	[39.947568, 116.387537],
	[39.947764, 116.401988],
	[39.947929, 116.410824],
	[39.947558, 116.42674],
	[39.9397, 116.427338],
	[39.932404, 116.427919],
	[39.923109, 116.428377],
	[39.907094, 116.429583],
	[39.906858, 116.41404],
	[39.906622, 116.405321],
	[39.906324, 116.394954],
	[39.906308, 116.391264],
	[39.916611, 116.390748],
];

// 创建地图
const createMap = () => {
	// 创建地图实例
	map = L.map('leafletMap', mapOptions);
	// 加载图层
	L.tileLayer(import.meta.env.VITE_GAODE_MAP, {
		// 如果设置此项为true，则切片不会用重复填充来表示世界范围（经度-180到180之间）之外的地方
		noWrap: true,
		// 左下角版权信息
		attribution,
	}).addTo(map);

	path = L.polyline(latlngs, {
		// 线宽
		weight: 5,
		// 颜色
		// color: '#FF9900',
	});
	//在起点处添加一个标注
	map.addLayer(L.marker(latlngs[0]));
	//在终点处添加一个标注
	map.addLayer(L.marker(latlngs[latlngs.length - 1]));
	//将线图层添加至地图中
	map.addLayer(path);
	// 开启水流模拟
	(path as any).snakeIn();
};

// 初始化地图
const initMap = () => {
	createMap();
};
// 创建地图
onMounted(() => {
	initMap();
});
// 销毁地图
onBeforeUnmount(() => {
	map?.remove();
	map = null;
});
</script>

<template>
	<div class="map-view">
		<div id="leafletMap" class="map"></div>
	</div>
</template>

<style lang="less" scoped>
@import url('./index.less');
</style>
